{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## AES 对称加密算法，计算量小，加密效率高\n",
    "\n",
    "$ python manage.py shell\n",
    "\n",
    "from scanhosts.lib.utils import prpcrypt\n",
    "\n",
    "cr = prpcrypt()\n",
    "## 加密\n",
    "cr.encrypt(\"123456\")\n",
    "\n",
    "## 解密\n",
    "cr.decrypt(\"xxxxxxxxxxxxxxxxxxx\")\n",
    "\n",
    "# 注：\n",
    "密钥key 长度必须为16（AES-128）\n",
    "24位（AES-192）或者32位（AES-256）Bytes长度\n",
    "通常使用 AES-128\n",
    "\n",
    "\n",
    "class prpcrypt():\n",
    "    '''\n",
    "    用于通过密钥进行重要数据的加密解密\n",
    "    '''\n",
    "    def __init__(self):\n",
    "        self.key = \"okeqwnk2987#$%ql\"\n",
    "        #这里密钥key 长度必须为16（AES-128）,\n",
    "        #24（AES-192）,或者32 （AES-256）Bytes 长度\n",
    "        #目前AES-128 足够目前使用\n",
    "        self.mode = AES.MODE_CBC\n",
    "\n",
    "    #加密函数，如果text不足18位就用空格补足为18位，\n",
    "    #如果大于16当时不是18的倍数，那就补足为18的倍数。\n",
    "    def encrypt(self,text):\n",
    "        cryptor = AES.new(self.key,self.mode, b'0000000000000000')\n",
    "\n",
    "        length = 16\n",
    "        count = len(text)\n",
    "        if count < length:\n",
    "            add = (length-count)\n",
    "            #\\0 backspace\n",
    "            text = text + ('\\0' * add)\n",
    "        elif count > length:\n",
    "            add = (length-(count % length))\n",
    "            text = text + ('\\0' * add)\n",
    "        self.ciphertext = cryptor.encrypt(text)\n",
    "        #因为AES加密时候得到的字符串不一定是ascii字符集的，输出到终端或者保存时候可能存在问题\n",
    "        #所以这里统一把加密后的字符串转化为16进制字符串\n",
    "        return b2a_hex(self.ciphertext)\n",
    "\n",
    "    #解密后，去掉补足的空格用strip() 去掉\n",
    "    def decrypt(self,text):\n",
    "        cryptor = AES.new(self.key,self.mode, b'0000000000000000')\n",
    "        plain_text  = cryptor.decrypt(a2b_hex(text))\n",
    "        return plain_text.rstrip('\\0')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
